<!-- src/views/Login.vue -->
<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="background">
      <div class="shape shape1"></div>
      <div class="shape shape2"></div>
      <div class="shape shape3"></div>
    </div>

    <!-- 登录卡片 -->
    <transition name="fade-slide">
      <div v-if="showCard" class="login-card">
        <div class="card-header">
          <div class="logo">
            <span class="logo-icon">🍿</span>
          </div>
          <h1>W 零食铺</h1>
          <p class="subtitle">后台管理系统</p>
        </div>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="rules"
          status-icon
          label-width="0"
          class="login-form"
        >
          <!-- 用户名 -->
          <transition name="slide-fade" appear>
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                autocomplete="off"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </transition>

          <!-- 密码 -->
          <transition name="slide-fade" appear>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                autocomplete="off"
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </transition>

          <!-- 验证码 -->
          <transition name="slide-fade" appear>
            <el-form-item prop="captcha">
              <el-row :gutter="12">
                <el-col :span="14">
                  <el-input
                    v-model="loginForm.captcha"
                    placeholder="请输入验证码"
                    autocomplete="off"
                  >
                    <template #prefix>
                      <el-icon><Picture /></el-icon>
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="10">
                  <div class="captcha-box" @click="refreshCaptcha">
                    <img
                      :src="captchaSrc"
                      alt="验证码"
                      class="captcha-img"
                      v-if="captchaSrc"
                    />
                    <div class="captcha-mask">
                      <el-icon><Refresh /></el-icon>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
          </transition>

          <!-- 错误提示 -->
          <transition name="fade" appear>
            <el-alert
              v-if="errorMsg"
              :title="errorMsg"
              type="error"
              show-icon
              class="login-error"
              :closable="false"
            />
          </transition>

          <!-- 登录按钮 -->
          <transition name="slide-fade" appear>
            <el-form-item>
              <el-button
                type="primary"
                class="login-button"
                :loading="loading"
                @click="handleSubmit"
              >
                登 录
              </el-button>
            </el-form-item>
          </transition>
        </el-form>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import router from "@/router";
import { useTokenStore } from "@/stores/useTokenStore";
import { User, Lock, Picture, Refresh } from "@element-plus/icons-vue";


import { getCaptchaImage, checkCaptcha, login } from "@/api/auth";

const tokenStore = useTokenStore();

// -------- 表单数据与校验规则 --------
const loginFormRef = ref(null);
const loginForm = ref({
  username: "",
  password: "",
  captcha: "",
});
const rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};

// -------- 组件内部状态 --------
const loading = ref(false);
const errorMsg = ref("");

// 验证码图片 src，从后端获取
const captchaSrc = ref("");
function loadCaptcha() {
  captchaSrc.value = getCaptchaImage();
}

// -------- 方法实现 --------
function refreshCaptcha() {
  loadCaptcha();
}

async function handleSubmit() {
  errorMsg.value = "";
  // 触发表单校验
  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return;

    loading.value = true;

    try {
      // 1. 校验验证码
      const checkRes = await checkCaptcha(loginForm.value.captcha);
      if (!checkRes.data) {
        errorMsg.value = checkRes.message || "验证码错误，请重试";
        refreshCaptcha();
        loading.value = false;
        return;
      }

      // 2. 调用登录接口
      const loginRes = await login({
        username: loginForm.value.username,
        password: loginForm.value.password,
      });
      const token = loginRes.data;
      if (!token) {
        errorMsg.value = loginRes.message || "用户名或密码错误";
        refreshCaptcha();
        loading.value = false;
        return;
      }

      // 3. 登录成功
      ElMessage.success("登录成功，即将跳转");
      console.log('登录成功，存储token:', !!token);
      
      // 存储token到pinia
      tokenStore.setToken(token);
      
      // 存储用户名
      localStorage.setItem('username', loginForm.value.username);
      
      // 检查token是否成功存储
      setTimeout(() => {
        console.log('跳转前检查token是否存储:', !!tokenStore.token);
        
        if (tokenStore.token) {
          // 确保token存在后再跳转
          router.push("/home");
        } else {
          ElMessage.error("登录数据存储失败，请重试");
          refreshCaptcha();
        }
      }, 800);
    } catch (err) {
      console.error(err);
      errorMsg.value = err.response?.data?.message || "网络或服务器错误";
      refreshCaptcha();
    } finally {
      loading.value = false;
    }
  });
}

// 添加控制卡片显示的变量
const showCard = ref(false);

// 修改 onMounted
onMounted(() => {
  loadCaptcha();
  // 延迟显示卡片，触发动画
  setTimeout(() => {
    showCard.value = true;
  }, 100);
});
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f6f8fa;
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.shape {
  position: absolute;
  border-radius: 50%;
  filter: blur(60px);
  opacity: 0.4;
  animation: float 8s infinite ease-in-out;
}

.shape1 {
  width: 300px;
  height: 300px;
  background: #4f46e5;
  top: -100px;
  left: -100px;
}

.shape2 {
  width: 400px;
  height: 400px;
  background: #7c3aed;
  bottom: -150px;
  right: -100px;
  animation-delay: -2s;
}

.shape3 {
  width: 200px;
  height: 200px;
  background: #2563eb;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-delay: -4s;
}

@keyframes float {
  0%, 100% {
    transform: translate(0, 0) scale(1) rotate(0deg);
  }
  50% {
    transform: translate(30px, 30px) scale(1.1) rotate(5deg);
  }
}

/* 登录卡片 */
.login-card {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  position: relative;
  z-index: 2;
}

/* 卡片头部 */
.card-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  width: 64px;
  height: 64px;
  background: #4f46e5;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 16px;
  animation: logoFloat 3s infinite ease-in-out;
}

.logo-icon {
  font-size: 32px;
}

.card-header h1 {
  font-size: 24px;
  color: #1f2937;
  margin-bottom: 8px;
}

.subtitle {
  color: #6b7280;
  font-size: 14px;
}

/* 表单样式 */
.login-form :deep(.el-input__wrapper) {
  background: #f9fafb;
  box-shadow: none;
  border: 1px solid #e5e7eb;
  height: 44px;
  border-radius: 8px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.login-form :deep(.el-input__wrapper:hover) {
  border-color: #4f46e5;
}

.login-form :deep(.el-input__wrapper.is-focus) {
  border-color: #4f46e5;
  box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.1);
  transform: translateY(-1px);
}

.login-form :deep(.el-input__prefix) {
  color: #9ca3af;
}

/* 验证码样式 */
.captcha-box {
  position: relative;
  height: 44px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #e5e7eb;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.captcha-box:hover {
  border-color: #4f46e5;
  transform: scale(1.02);
}

.captcha-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.captcha-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.captcha-mask .el-icon {
  color: white;
  font-size: 20px;
  transition: transform 0.3s ease;
}

.captcha-box:hover .captcha-mask {
  opacity: 1;
}

.captcha-box:hover .captcha-mask .el-icon {
  transform: rotate(180deg);
}

/* 错误提示 */
.login-error {
  margin-bottom: 20px;
  border-radius: 8px;
}

/* 登录按钮 */
.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  background: #4f46e5;
  border: none;
  border-radius: 8px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.login-button:hover {
  background: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}

.login-button:active {
  transform: translateY(1px);
}

/* 响应式设计 */
@media screen and (max-width: 640px) {
  .login-card {
    width: 90%;
    padding: 30px;
  }
}

/* 卡片淡入动画 */
.fade-slide-enter-active {
  transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}
.fade-slide-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

/* 表单项滑入动画 */
.slide-fade-enter-active {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}
.slide-fade-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

/* 为每个表单项添加延迟 */
.login-form .el-form-item:nth-child(1) {
  transition-delay: 0.1s;
}
.login-form .el-form-item:nth-child(2) {
  transition-delay: 0.2s;
}
.login-form .el-form-item:nth-child(3) {
  transition-delay: 0.3s;
}
.login-form .el-form-item:nth-child(4) {
  transition-delay: 0.4s;
}

/* 错误提示淡入动画 */
.fade-enter-active {
  transition: all 0.3s ease;
}
.fade-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}

/* 增强背景动画效果 */
.shape {
  animation: float 8s infinite ease-in-out;
}
.shape1 {
  animation-delay: 0s;
}
.shape2 {
  animation-delay: -2s;
}
.shape3 {
  animation-delay: -4s;
}

@keyframes float {
  0%, 100% {
    transform: translate(0, 0) scale(1) rotate(0deg);
  }
  50% {
    transform: translate(30px, 30px) scale(1.1) rotate(5deg);
  }
}

/* 增强 logo 动画 */
.logo {
  animation: logoFloat 3s infinite ease-in-out;
}

@keyframes logoFloat {
  0%, 100% {
    transform: translateY(0) scale(1);
  }
  50% {
    transform: translateY(-5px) scale(1.05);
  }
}

/* 增强按钮悬停效果 */
.login-button {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}
.login-button:active {
  transform: translateY(1px);
}

/* 增强验证码刷新效果 */
.captcha-box {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.captcha-box:hover {
  transform: scale(1.02);
}
.captcha-mask {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.captcha-mask .el-icon {
  transition: transform 0.3s ease;
}
.captcha-box:hover .captcha-mask .el-icon {
  transform: rotate(180deg);
}

/* 输入框焦点动画 */
.login-form :deep(.el-input__wrapper) {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.login-form :deep(.el-input__wrapper.is-focus) {
  transform: translateY(-1px);
}
</style>
  